package com.ihighest.app.infox.activity;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.RegexKit;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;

/**
 * 注册界面
 * 
 * @author lkx Created at 2015-10-3 下午8:47:41
 * @version 1.0
 */
public class RegisterActivity extends BaseActivity implements OnClickListener {

	final static String TAG = "RegisterActivity";

	private ActivityTitle title;

	private EditText phoneNumberEditText, codeEditText, psdEditText, ensurePsd;
	private Button getcodeButton, registerbButton;
	private String phonenumber, password;
	private EditText inviteNumberEditText;

	private String codeId = null;
	private int time = 0;

	private Handler handler;

	private Timer timer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.infox_activity_register);
		title = (ActivityTitle) findViewById(R.id.infox_registerActivity_title);
		title.setTitle("注册新用户");
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("取消");

		intint();
	}

	private void intint() {

		phoneNumberEditText = (EditText) findViewById(R.id.infox_register_userPhone);
		codeEditText = (EditText) findViewById(R.id.infox_register_textcode);
		psdEditText = (EditText) findViewById(R.id.edittextpsd);
		ensurePsd = (EditText) findViewById(R.id.editNewPsdAgain);
		getcodeButton = (Button) findViewById(R.id.button1);
		registerbButton = (Button) findViewById(R.id.infox_register_btnRegister);
		timer = new Timer();
		inviteNumberEditText = (EditText) findViewById(R.id.invitedit);
		getcodeButton.setOnClickListener(this);
		registerbButton.setOnClickListener(this);
		findViewById(R.id.infox_register_aggrement).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(RegisterActivity.this, RegisterAgreeActivity.class);
				startActivity(intent);
			}
		});

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {
				case 0x147:
					if (time != 0) {
						getcodeButton.setText(time + "s后重新获取");

					}
					break;
				case 0x148:
					if (time <= 0) {

						timer.cancel();
						getcodeButton.setText("重新发送");
						getcodeButton.setClickable(true);
						getcodeButton.setBackgroundResource(R.drawable.infox_content_comment_bg);

					} else {

						time = time - 1;
						getcodeButton.setText(time + "s后重新获取");
					}

					break;

				}

			}
		};
		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();

			}
		});
	}

	@Override
	public void onClick(View arg0) {
		phonenumber = phoneNumberEditText.getText().toString();
		if (TextUtils.isEmpty(phonenumber) || !RegexKit.isMobile(phonenumber)) {
			ToastKit.showShort(RegisterActivity.this, "请输入正确手机号");
			return;
		}

		switch (arg0.getId()) {
		// getcode
		case R.id.button1:

			Api.post("mobilecaptcha", ApiParam.create().addParam("phone", phonenumber).addParam("type", "register"), new ApiCallback(this) {

				@Override
				public void handleSuccess(ApiResult result) {
					try {
						if (result.getCode() == 100) {
							codeId = result.getData().getString("captcha_id");
							time = result.getData().getInt("time");
							getcodeButton.setClickable(false);
							getcodeButton.setBackgroundResource(R.drawable.infox_register_btn_gettextcode_bg);
							handler.sendEmptyMessage(0x147);
							task();
						} else {
							ToastKit.showShort(RegisterActivity.this, TextUtils.isEmpty(result.getMsg()) ? "获取验证码失败" : result.getMsg());
						}
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}

				}

				private void task() {
					timer.schedule(new TimerTask() {

						@Override
						public void run() {

							handler.sendEmptyMessage(0x148);
						}

					}, 1000, 1000);

				}

				@Override
				public void handleFailure(Exception e, String msg) {
				}
			}, this);

			break;
		// register
		case R.id.infox_register_btnRegister:

			registerbButton.setClickable(false);
			if (codeEditText.getText().toString().equals("") || codeEditText.getText().toString() == null) {
				ToastKit.showShort(RegisterActivity.this, "验证码不能为空");
			} else if (!RegexKit.isPassword(psdEditText.getText().toString())) {
				ToastKit.showShort(RegisterActivity.this, "密码为6到20位数字或字母");
			} else if (TextUtils.isEmpty(ensurePsd.getText().toString())) {
				ToastKit.showShort(RegisterActivity.this, "请再次确认密码");
			} else if (!ensurePsd.getText().toString().endsWith(psdEditText.getText().toString())) {
				ToastKit.showShort(RegisterActivity.this, "两次密码输入不一致");
			} else {

				ApiParam param = ApiParam.create().addParam("mobile", phonenumber)
						.addParam("password", AppKit.md5(psdEditText.getText().toString()))
						.addParam("captcha", codeEditText.getText().toString()).addParam("captcha_id", codeId);
				if (inviteNumberEditText.getText().toString().equals("") || inviteNumberEditText.getText().toString() == null) {

				} else {
					param.addParam("invitationCode", inviteNumberEditText.getText().toString());
				}

				Api.post("register", param, new ApiCallback(this) {

					@Override
					public void handleSuccess(ApiResult result) {
						if (result.getCode() == 100) {
							try {
								SharedPreferencesKit.putString(getApplicationContext(), Const.SP_KEY_LAST_LOGIN_KEY, phonenumber);
								SharedPreferencesKit.putString(getApplicationContext(), Const.SP_KEY_LAST_LOGIN_PWD, psdEditText.getText()
										.toString());

								// 存储当前登录用户信息
								AppKit.storeUserInfo(getApplicationContext(), result.getData());

								// 链接融云
								AppKit.connectRongIM(getApplicationContext(), result.getData().getString("rtoken"));

								ToastKit.showLong(RegisterActivity.this, "注册成功");
								timer.cancel();
								// Umeng push
								final String uid = SharedPreferencesKit.getString(mContext, Const.SP_KEY_USER_ID);
								final String mid = SharedPreferencesKit.getString(mContext, Const.SP_KEY_USER_MID);
								new Thread(new Runnable() {

									@Override
									public void run() {
										try {
											PushAgent.getInstance(getApplicationContext()).addAlias(uid, "AID");
											PushAgent.getInstance(getApplicationContext()).addAlias(mid, "MID");
											if (SharedPreferencesKit.getBoolean(getApplicationContext(), Const.SP_ACCEPTINFOMATION, true)) {
												SharedPreferencesKit.putBoolean(getApplicationContext(), Const.SP_ACCEPTINFOMATION, true);
												Api.post("me/setting", ApiParam.create().addParam("key", Const.SP_ACCEPTINFOMATION)
														.addParam("value", String.valueOf(true)), new ApiCallback(RegisterActivity.this,
														true) {

													@Override
													public void handleSuccess(ApiResult result) {

													}

													@Override
													public void handleFailure(Exception e, String msg) {

													}
												}, RegisterActivity.this);
												if (PushAgent.getInstance(getApplicationContext()).isEnabled()) {
													PushAgent.getInstance(getApplicationContext()).disable();
												}
												PushAgent.getInstance(getApplicationContext()).enable();
												Log.d(TAG, "RegistrationId --> " + UmengRegistrar.getRegistrationId(mContext));
											} else {
												if (PushAgent.getInstance(getApplicationContext()).isEnabled()) {
													PushAgent.getInstance(getApplicationContext()).disable();
												}
											}
										} catch (Exception ex) {
											Log.e(TAG, ex.getMessage(), ex);
										}

									}
								}).start();

							} catch (Exception e) {
								Log.e(TAG, e.getMessage(), e);
							}

							Intent intent = new Intent(RegisterActivity.this, SetNameAndIconActivity.class);
							startActivity(intent);
							registerbButton.setClickable(true);
							finish();

						} else {
							ToastKit.showShort(RegisterActivity.this, TextUtils.isEmpty(result.getMsg()) ? "注册失败" : result.getMsg());
							registerbButton.setClickable(true);
							return;
						}

					}

					@Override
					public void handleFailure(Exception e, String msg) {

						// 注册失败重新注册
						ToastKit.showShort(RegisterActivity.this, msg.toString());
						registerbButton.setClickable(true);
					}
				}, this);
			}
			registerbButton.setClickable(true);
			break;
		}
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

}
